package com.cwnu.sw.cys.core.user.service.adapter;

import cn.hutool.core.util.RandomUtil;
import com.cwnu.sw.cys.core.common.domain.enums.YesOrNoEnum;
import com.cwnu.sw.cys.core.common.domain.vo.resp.UserInfoResp;
import com.cwnu.sw.cys.core.user.domain.entity.ItemConfig;
import com.cwnu.sw.cys.core.user.domain.entity.User;
import com.cwnu.sw.cys.core.user.domain.entity.UserBackpack;
import com.cwnu.sw.cys.core.user.domain.vo.resp.BadgeResp;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import org.springframework.beans.BeanUtils;

import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author jisam
 * @version 1.0
 * @contact "jisamchan@outlook.com"
 * @date 13/02/2025
 * @description 用户适配器
 */
public class UserAdapter {
    public static User builderUserSave(String openId) {
        return User.builder()
                .openId(openId)
                .build();
    }
    public static User buildAuthUser(Long uid, WxOAuth2UserInfo userInfo) {
            User user = new User();
            user.setId(uid);
            user.setAvatar(userInfo.getHeadImgUrl());
            user.setName(userInfo.getNickname());
            user.setSex(userInfo.getSex());
            if (userInfo.getNickname().length() > 6) {
                user.setName("名字过长" + RandomUtil.randomInt(100000));
            } else {
                user.setName(userInfo.getNickname());
            }
            return user;
    }

    public static UserInfoResp builderUserInfoResp(User userById, Integer countByValue) {
        UserInfoResp userInfoResp = new UserInfoResp();
        BeanUtils.copyProperties(userById, userInfoResp);
        userInfoResp.setModifyNameChance(countByValue);
        return userInfoResp;
    }

    public static List<BadgeResp> builderBadgeResp(List<ItemConfig> itemConfigs, List<UserBackpack> backpacks, User user) {
        List<Long> obtainSet = backpacks.stream().map(UserBackpack::getItemId).collect(Collectors.toList());
        return itemConfigs.stream().map(a -> {
                    BadgeResp badgeResp = new BadgeResp();
                    BeanUtils.copyProperties(a, badgeResp);
                    badgeResp.setObtain(obtainSet.contains(a.getId()) ? YesOrNoEnum.YES.getStatus() : YesOrNoEnum.NO.getStatus());
                    badgeResp.setWearing(Objects.equals(a.getId(), user.getItemId()) ? YesOrNoEnum.YES.getStatus() : YesOrNoEnum.NO.getStatus());
                    return badgeResp;
                }).sorted(Comparator.comparing(BadgeResp::getWearing, Comparator.reverseOrder()).
                        thenComparing(BadgeResp::getObtain, Comparator.reverseOrder()))
                .collect(Collectors.toList());

    }
}
